import type {GetProp, UploadFile, UploadProps} from 'antd';
import {Image, Upload} from "antd";
import {useEffect, useState} from "react";
import {PlusOutlined} from "@ant-design/icons";
import {deleteFileUrl, uploadProjectUrl} from "@/api/file.ts";
import {globalMessageApi} from "@/components/OpComponent/Message";

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

export type FileListType = {
    uid: string,
    name: string,
    status: string,
    url: string,
}

const getBase64 = (file: FileType): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = (error) => reject(error);
    });

export default function UploadPicture(props: any) {
    const {
        fileList = [],
        setStatus,
        url,
    } = props

    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [_fileList, setFileList] = useState<UploadFile[]>(fileList);

    useEffect(() => {
        setFileList(fileList)
    }, [fileList])


    useEffect(() => {
        if(setStatus) setStatus(true)
    }, [_fileList])

    //     [
    //     {
    //         uid: '-1',
    //         name: 'image.png',
    //         status: 'done',
    //         url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    //     },
    // ]


    // 将 fileList 和 _fileList 绑定

    const handlePreview = async (file: UploadFile) => {
        console.log("handlePreview", file)
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as FileType);
        }
        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
    };

    const handleChange: UploadProps['onChange'] = ({fileList: newFileList}) => {
        const fileList: any[] = newFileList.map((file) => {
            const res = file.response
            if (res) {
                return {
                    ...file,
                    uid: res.uid
                }
            }
            return file
        })
        setFileList(fileList);
    }


    const uploadButton = (
        <button style={{border: 0, background: 'none'}} type="button">
            <PlusOutlined/>
            <div style={{marginTop: 8}}>Upload</div>
        </button>
    );

    const handleCustomRequest = async (options: any) => {
        const {file, onSuccess, onError} = options
        const formData = new FormData();
        formData.append('files', file, file.name);
        return new Promise((resolve, reject) => {
            uploadProjectUrl(url, formData).then((res: any) => {
                globalMessageApi.success(res.msg)
                resolve(res)
                onSuccess({
                    url: res.data[0].url,
                    uid: res.data[0].id,
                    name: res.data[0].name,
                    fileName: res.data[0].fileName,
                    status: 'done',
                })
            }).catch(() => {
                alert("上传失败")
                reject(false)
                onError()
            })
        })
    }

    const handleBeforeUpload = (file: any, fileList: any) => {
        console.log("handleBeforeUpload", file, fileList)
        // 遍历 fileList 对文件进行校验，要求文件必须是图片，并且每个文件大小不能超过 2M
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            alert('上传文件大小不能超过 2MB!');
            return false;
        }
        return true;
    }

    const handleOnRemove = (file: any): any => {
        console.log("handleOnRemove", file)
        return new Promise((resolve, reject) => {
            deleteFileUrl(file.uid).then((res: any) => {
                globalMessageApi.success(res.msg)
                resolve(true)
            }).catch(() => {
                alert("删除失败")
                reject(false)
            })
        })
    }

    return <>
        <Upload
            beforeUpload={handleBeforeUpload}
            customRequest={handleCustomRequest}
            listType="picture-card"
            fileList={_fileList}
            onPreview={handlePreview}
            onChange={handleChange}
            onRemove={handleOnRemove}
            maxCount={1}
        >
            {_fileList.length >= 8 ? null : uploadButton}
        </Upload>
        {previewImage && (
            <Image
                wrapperStyle={{display: 'none'}}
                preview={{
                    visible: previewOpen,
                    onVisibleChange: (visible) => setPreviewOpen(visible),
                    afterOpenChange: (visible) => !visible && setPreviewImage(''),
                }}
                src={previewImage}
            />
        )}

    </>
}
